package in.hitmedia.test.trees;

public class Tree<T extends Comparable<T>>
{
	private Node<T> root = null;
	
	public Tree(T a[])
	{
		
		for (int i=0; i < a.length; ++i)
		{
			root = add(root, a[i]);
		}
		
	}
	
	public void printPreOrder()
	{
		System.out.println("\nPreOrder\n");
		preOrder(root);
	}
	
	public void printPostOrder()
	{
		System.out.println("\nPostOrder\n");
		postOrder(root);
	}
	
	public void printInOrder()
	{
		System.out.println("\nInOrder\n");
		inOrder(root);
	}
	
	private void preOrder(Node<T> t)
	{
		if (t != null)
		{
			System.out.println(t.val);
			preOrder(t.left);
			preOrder(t.right);
		}
	}
	
	private void inOrder(Node<T> t)
	{
		if (t != null)
		{
			inOrder(t.left);
			System.out.println(t.val);
			inOrder(t.right);
		}
	}
	
	private void postOrder(Node<T> t)
	{
		if (t != null)
		{
			postOrder(t.left);
			postOrder(t.right);
			System.out.println(t.val);
		}
	}
	
	public Node<T> add(Node<T> n , T key)
	{
		if (n == null)
		{
			Node<T> node = new Node<T>(key, ""+key);
			return node;
		}
		else if (key.compareTo(n.key) == 0)
		{
			n.key = key;
			return n;
		}
		else if (key.compareTo(n.key) < 0)
		{
			n.left = add(n.left, key);
			return n;
		}
		else 
		{
			n.right = add(n.right, key);
			return n;
		}
			 
	}
	
	public static void main(String args[])
	{
		Long a[] = {3L, 1L, 2L, 8L, 6L, 7L};
		Tree<Long> tree = new Tree<Long>(a);
		
		tree.printPreOrder();
		tree.printInOrder();
		tree.printPostOrder();
		
	}
	

}
